import pandas as pd
import time
import re
import os
import gc
import numpy
from sklearn import tree
from sklearn.datasets import load_wine
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import roc_curve  # 导入ROC曲线函数

from sklearn import tree

from sklearn.metrics import make_scorer

from sklearn.metrics import auc

#
# 使用决策树算法对电力窃漏电数据集建模
#
#
# 1、数据划分 取30%做测试样本，剩下做训练样本
# 2、CART决策树（分类树）
# 3、生成混淆矩阵
# 4、计算预测准确率
# 5、进行交叉验证
# 6、画出“受试者工作特征”曲线，即ROC曲线
#
# def fuc1():
#     print(1)







if __name__ == '__main__':
    # fuc1(np,pd,sk)
    print(1)
    data = pd.read_excel("dataset.xls", sheet_name = 0)
    # 1、数据划分
    # 取30 % 做测试样本，剩下做训练样本
    print("数据划分")

    wine = load_wine()
    # df2 = data.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
    # print(data)
    # xtain,xtest,ytrain,ytest = train_test_split(data.loc[:,:-1],data.loc[:,-1],test_size=0.3)
    xtain,xtest,ytrain,ytest = train_test_split(data.loc[:,['电量趋势下降指标','线损指标','告警类指标']],data['是否窃漏电'],test_size=0.3)

    # print(data.loc[:,[-1]])
    # print(data.loc[:,:-1])
    # print(data.columns)
    # print(data['是否窃漏电'])
    # print(data.loc[:,['电量趋势下降指标','线损指标','告警类指标']])
    # print(xtest)

    #2、CART决策树（分类树）
    print("CART决策树")

    clf = tree.DecisionTreeClassifier(criterion='gini')
    clf = clf.fit(xtain,ytrain)
    print(clf.score(xtest,ytest))
    # 3、生成混淆矩阵
    print("生成混淆矩阵")

    r = metrics.confusion_matrix(ytest,clf.predict(xtest))
    print(r)
    #4、计算预测准确率
    rs = metrics.accuracy_score(ytest,clf.predict(xtest))
    print("计算预测准确率")
    print(rs)
    #5、进行交叉验证
    print("进行交叉验证")
    from sklearn.metrics import r2_score

    # print(r2_score(y_test, dt_fit.predict(X_test)))
    # print(dt_fit.score(X_test, y_test))
    scoring = make_scorer(r2_score)
    g_cv = GridSearchCV(DecisionTreeRegressor(random_state=0),
                        param_grid={'min_samples_split': range(2, 10)},
                        scoring=scoring, cv=5, refit=True)
    g_cv.fit(xtain, ytrain)
    g_cv.best_params_

    result = g_cv.cv_results_
    # print(result)
    e = r2_score(ytest, g_cv.best_estimator_.predict(xtest))
    print(e)
    # 6、画出“受试者工作特征”曲线，即ROC曲线
    print("画出“受试者工作特征”曲线，即ROC曲线")
    # roc_auc = auc(fpr, tpr)
    # plt.plot(fpr, tpr, 'k--', label='ROC (area = {0:.2f})'.format(roc_auc), lw=2)

    # fpr, tpr, thresholds = metrics.roc_curve(data.loc[:,['电量趋势下降指标','线损指标','告警类指标']], data['是否窃漏电'], pos_label=2)
    # plt.plot(fpr, tpr, marker='o')
    #
    # plt.show()
    # fpr,tpr,thresholds = roc_curve(ytest,)


    def plot_roc(ytest, predict_result, label_name):
        from sklearn.metrics import roc_curve  # 导入ROC曲线函数

        fpr, tpr, thresholds = roc_curve(
            ytest, predict_result, pos_label=1)
        plt.plot(fpr, tpr, linewidth=2, label='ROC of CART', color='green')  # 作出ROC曲线
        plt.xlabel('False Positive Rate')  # 坐标轴标签
        plt.ylabel('True Positive Rate')  # 坐标轴标签
        plt.ylim(0, 1.05)  # 边界范围
        plt.xlim(0, 1.05)  # 边界范围
        plt.legend(loc=4)  # 图例
        plt.show()  # 显示作图结果
        return plt


    predict_result = clf.predict(xtest)
    plot_roc(ytest, predict_result, 'ROC of CART')
